package com.tal.pad.orc.base.net;

import com.tal.bcc.pad.cloud.upload.HttpRequestParams;
import com.tal.bcc.pad.cloud.utils.DateUtils;
import com.tal.bcc.pad.cloud.utils.JsonUtil;
import com.tal.bcc.pad.cloud.utils.RequestMethod;
import com.tal.bcc.pad.cloud.utils.SignatureSDK;
import com.tal.pad.orc.base.AppConfig;
import com.tal.pad.orc.base.utils.LogUtils;
import okhttp3.*;
import org.apache.http.util.TextUtils;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;


public class OCRUtils {

    public static final int ERROR_TYPE_NONE = 0;
    public static final int ERROR_TYPE_NOPERMISSION = 1;
    public static final int ERROR_TYPE_IMG_ERROR = 2;//图片处理错误
    public static final int ERROR_TYPE_UPLOAD_ERROR = 3;//图片处理错误
    public static final int ERROR_TYPE_OCR_ERROR = 4;//ocr错误
    public static final int ERROR_TYPE_OCR_FAILURE = 5;//ocr业务成功，识别结果为空

    public static final String TAG = "CameraAnswerHelper";
    private final String ACCESS_KEY_ID = "1057704529430056960";
    private final String ACCESS_KEY_SECRET = "f11cfdce027f48379c874e9bf7fa6efd";
    private final String AIOCR_COMMON_DETECT = "http://openai.100tal.com/aiimage/aiocr/common-detect";//aiocr检测地址
    private final int MAX_FILE_SIZE = 2;//图片上传限制2M
    private final int RETRY_COUNT = 3;

    /**
     * 设置超时的OkHttpClient
     */
    private static WeakHashMap<String, OkHttpClient> weakHashMap = new WeakHashMap<>();
    //private static WeakReference<MockInterceptor> mockHttpInterceptorWeakRef;

    public static final MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
    protected static OkHttpClient okHttpClient;
    private static boolean isOpenHttpDNS;//是否开启NDS，配置中心控制
    static final String DEFAULT_HTTP_CLIENT_KEY = "default";//http client 默认的key


    static {
        long before = System.currentTimeMillis();
        //初始化okHttp并设置超时时间
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (AppConfig.DEBUG) {
            // builder.addInterceptor(newLoggingInterceptor());
        }
        builder.dispatcher(OkHttpClientHelper.getDefaultDispatcher()); //通过自定义线程池调用Ok

        X509TrustManager x509TrustManager = SSLSocketClient.initX509TrustManager();
        SSLSocketFactory sslSocketFactory = null;
        try {
            sslSocketFactory = SSLSocketClient.initSSLFactory(x509TrustManager);
        } catch (Exception e) {

        }
        NetWorkConfig.getNetWorkConfigRemoteInfo();//获取网络配置
        builder = builder.connectTimeout(NetWorkConfig.configInfo.getConnectTime(), TimeUnit.SECONDS)
//                .protocols()
                .readTimeout(NetWorkConfig.configInfo.getReadTimeout(), TimeUnit.SECONDS)
                .writeTimeout(NetWorkConfig.configInfo.getWriteTimeout(), TimeUnit.SECONDS)
                .retryOnConnectionFailure(true);
//                .addInterceptor(new CheckTimeCountInterceptor())//重试监
                //.addInterceptor(new XesRetryInterceptor(NetWorkConfig.configInfo.retryNum))//重试监听
                //.addInterceptor(new RetryInterceptor(NetWorkConfig.configInfo.retryNum))//重试监听
                //.sslSocketFactory(sslSocketFactory,x509TrustManager)
                //.sslSocketFactory(new SSLSocketClient().getSSLSocketFactory())
                //.hostnameVerifier(new SSLSocketClient().getHostnameVerifier())//忽略验证证书
                //.addInterceptor(new HTTPDNSInterceptor())//HTTPDNS拦截器
//                .eventListenerFactory(HttpEventListener.FACTORY)
//                .addInterceptor(new LogMonitorInterceptor());
        //先去掉
//                .addInterceptor(new DataPreloadInterceptor());

//        if (!AppConfig.isPulish) {
//            mockHttpInterceptorWeakRef = new WeakReference<>(new MockInterceptor());
//            builder.addInterceptor(mockHttpInterceptorWeakRef.get()); //mock
////            builder.addInterceptor(AsProfilerManager.getInstance().createLogRecordInterceptor());
//        }


//        builder = builder.dns(AlHttpDns.getInstance());
        okHttpClient = builder.build();
        //change by lizheng on 2021/4/23 des: 增加 okhttp 同host 下最大请求数到12
        weakHashMap.put(DEFAULT_HTTP_CLIENT_KEY, okHttpClient);
        okHttpClient.dispatcher().setMaxRequestsPerHost(12);

//        logger.d("BaseHttp:time=" + (System.currentTimeMillis() - before));
    }

    /**
     * 请求ocr接口
     *
     * @param imageUrl
     * @param httpCallBack
     */
    public void requestOcr(String imageUrl, Callback httpCallBack) {
        HttpRequestParams httpRequestParams = new HttpRequestParams();
        httpRequestParams.setCloseDefaultParams(true);
        httpRequestParams.addHeaderParam("Content-Type", "application/json;charset=UTF-8");

        RequestOcrParams params = new RequestOcrParams();
        params.image_url = imageUrl;

        httpRequestParams.setJson(JsonUtil.toJson(params));

        Map<String, Object> urlParams = new HashMap<>();
        Map<String, Object> bodyParams = new HashMap<>();
        bodyParams.put("image_url", imageUrl);

        String timestamp = DateUtils.getCurrentDate();

        SignatureSDK.getSignature(ACCESS_KEY_ID, ACCESS_KEY_SECRET, timestamp, urlParams, bodyParams, RequestMethod.POST, SignatureSDK.APPLICATION_JSON);

        String url = AIOCR_COMMON_DETECT + "?" + SignatureSDK.urlParamsFormat(urlParams);
//        mHttpManager.sendJsonPost(url, httpRequestParams, httpCallBack);
        Request request = createBaseJsonSendPostRequest(url, httpRequestParams, httpCallBack);
        OkHttpClient eagerClient = getOkHttpClient(httpRequestParams);
        //发送异步请求
        Call call = eagerClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                LogUtils.getLogUtils().info(TAG,"requestOcr response:" + response.body().string());
            }
        });

    }

    private Request createBaseJsonSendPostRequest(String url, HttpRequestParams httpRequestParams, Callback httpCallBack) {
        //构建post的传参
        Request.Builder requestBuilder = null;
        // 如果请求参数中，有自定义参数对象，则请求body 参数为该json
        if (!TextUtils.isEmpty(httpRequestParams.getJson())) {

            RequestBody requestBody = RequestBody.create(jsonType, httpRequestParams.getJson());
            requestBuilder = new Request.Builder().url(url).post(requestBody);
        } else {
            //如果请求参数中，没有自定义参数对象。则对默认body Map 对象进行转json操作
            RequestBody requestBody = RequestBody.create(jsonType,
                    JsonUtil.objectToJson(httpRequestParams.getBodyParams()));
            requestBuilder = new Request.Builder().url(url).post(requestBody);
        }
        if (requestBuilder != null) {
            //添加header参数
            if (httpRequestParams != null && httpRequestParams.getHeaderParams() != null) {
                Set<Map.Entry<String, String>> entries = httpRequestParams.getHeaderParams().entrySet();
                for (Map.Entry<String, String> entry : entries) {
                    if (entry.getValue() != null && !"null".equals(entry.getValue())) {
                        String key = entry.getKey();
                        requestBuilder.addHeader(entry.getKey(), entry.getValue());
                    } else {
                        requestBuilder.addHeader(entry.getKey(), "");
                    }
                }
            }
            return requestBuilder.build();
        }
        return null;
    }

    protected static OkHttpClient getOkHttpClient(HttpRequestParams httpRequestParams) {
        return getOkHttpClient(httpRequestParams, true);
    }


    private static OkHttpClient getOkHttpClient(HttpRequestParams httpRequestParams, boolean retry) {
        int writeAndreadTimeOut = httpRequestParams.getWriteAndreadTimeOut();
        OkHttpClient eagerClient = null;
        if (writeAndreadTimeOut > 0) {
            eagerClient = weakHashMap.get(String.valueOf(httpRequestParams.getWriteAndreadTimeOut()));
        } else {
            eagerClient = weakHashMap.get(DEFAULT_HTTP_CLIENT_KEY);
        }

        if (eagerClient == null) {
            OkHttpClient.Builder builder1 = okHttpClient.newBuilder();
//            if (AppConfig.DEBUG) {
//                builder1.addInterceptor(newLoggingInterceptor());
//            }

            builder1 = builder1.connectTimeout(httpRequestParams.getWriteAndreadTimeOut(), TimeUnit.SECONDS)
                    .readTimeout(httpRequestParams.getWriteAndreadTimeOut(), TimeUnit.SECONDS)
                    //.addInterceptor(new XesRetryInterceptor(NetWorkConfig.configInfo.retryNum))//重试拦截器
                    //默认的builder1已经添加，不用重复添加。
//                    .addInterceptor(new RetryInterceptor(NetWorkConfig.configInfo.retryNum))//重试监听
                    .writeTimeout(httpRequestParams.getWriteAndreadTimeOut(), TimeUnit.SECONDS)
                    .retryOnConnectionFailure(retry);
//                    .eventListenerFactory(HttpEventListener.FACTORY);
            //这样每次都会添加一个
//                    .addInterceptor(new LogMonitorInterceptor());

       /*     if (isOpenHttpDNS) {
                //增加httpDNS服务
                builder1 = builder1.dns(new OkHttpDns());
            }*/
//        if (isOpenHttpDNS) {
//            //增加httpDN服务
//            builder1 = builder1.dns(new XesHttpDns());
//        } else {
//            builder1 = builder1.dns(AlHttpDns.getInstance());
//        }

//            builder1.dispatcher(OkHttpClientHelper.getDefaultDispatcher()); //通过自定义线程池调用Ok
            builder1.followRedirects(true);
            eagerClient = builder1.build();
            weakHashMap.put("" + httpRequestParams.getWriteAndreadTimeOut(), eagerClient);
            //change by lizheng on 2021/4/23 des:增加okhttp 同host 下最大请求数
            eagerClient.dispatcher().setMaxRequestsPerHost(12);
        }
        return eagerClient;
    }

}
